﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using PPAP.BO;

namespace PPAP.Web.Frames
{
    public partial class Help : PageBase
    {
        public string FJID { set; get; }
        public string GID { set; get; }
        LogBO lbo = new LogBO();
        T_FileBO manager = new T_FileBO();
        UsersBO ubo = new UsersBO();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (!ubo.IsAdmin(CurrentUser.Id))
                {
                    trTemplate.Visible = false;
                    GridView2.Columns[7].Visible = false;
                }
                GetFile("");
            }
            if (Request.QueryString["GID"] != null)
            {
                GID = Request.QueryString["GID"].ToString();
            }
            if (Request.QueryString["deid"] != null)
            {
                DeleteFile(Request.QueryString["deid"].ToString());
            }
        }

        public void GetFile(string sort)
        {
            string fjid1 = "", fjid2 = "";
            if (Request.QueryString["GID"] != null && Request.QueryString["GID"].ToString() == "Guide")
            {
                fjid1 = "240FCB8F-15EF-418F-88B8-70BBBAC4370E"; fjid2 = "0702CDBA-EE6E-4846-84B0-98D1A9F870BC";
            }
            else
            {
                fjid1 = "CD8869A4-1B43-4086-A65B-C808944673E1"; fjid2 = "D5AC7FB1-9882-4FA0-B4C5-F49F81BF4EB4";
            }
            DataSet ds = null;
            if (CurrentUser.UnitId == "0" || CurrentUser.UnitId == "99")
                ds = manager.GetFileListForWhere(string.Format(" F_FileID='{0}' ",fjid1),sort);
            else
                ds = manager.GetFileListForWhere(string.Format(" (F_FileID='{0}' or F_FileID='{1}' )",fjid1,fjid2),sort);
            if (ds.Tables[0].Rows.Count == 0)
            {
                DataRow dr = ds.Tables[0].NewRow();
                dr["F_Filename"] = "<font color='red'>No files available</font>";
                ds.Tables[0].Rows.Add(dr);
            }
            AspNetPager2.RecordCount = ds.Tables[0].Rows.Count;
            GridView2.DataSource = GetPageTable(ds.Tables[0], AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
            GridView2.DataBind();
        }
        protected void AspNetPager2_PageChanged(object sender, EventArgs e)
        {
            BindGridView();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="fileid"></param>
        private void DeleteFile(string fileid)
        {
            try
            {
                DataSet ds = manager.Getpath(int.Parse(fileid));
                string path = ds.Tables[0].Rows[0]["F_Detail"].ToString();

                if (manager.DeleteFile(fileid))
                {
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }

                    //AlertReLoad("Deleted successful");
                    AlertRedirect("Deleted successful", "Help.aspx?GID=" + Request.QueryString["GID"].ToString());
                    //AlertRedirect("Deleted successful", "Template.aspx");
                    //AlertBack("Deleted successful");
                }

            }
            catch (Exception)
            {

                throw;
            }
        }

        //添加操作
        private void DataInfo(string F_FileID, string F_Filename, string path, int type, string url, string filesize, string remarks, string upby)
        {
            manager.InsertFile(F_FileID, F_Filename, path, type, url, filesize, remarks, upby, rbt1.Checked ? "File for supplier" : "File for BDNT", "", "");
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            //Model.AttachmentTemplate d = bo.GetModel(int.Parse(Request.QueryString["DID"].ToString()));
            if (true)
            {
                string fjid1 = "", fjid2 = "";
                if (Request.QueryString["GID"] != null && Request.QueryString["GID"].ToString() == "Guide")
                {
                    fjid1 = "240FCB8F-15EF-418F-88B8-70BBBAC4370E"; fjid2 = "0702CDBA-EE6E-4846-84B0-98D1A9F870BC";
                }
                else
                {
                    fjid1 = "CD8869A4-1B43-4086-A65B-C808944673E1"; fjid2 = "D5AC7FB1-9882-4FA0-B4C5-F49F81BF4EB4";
                }

                FJID = rbt1.Checked ? fjid1:fjid2;
                string FileName = file.FileName;
                if (!string.IsNullOrEmpty(FileName))
                {
                    string extension = System.IO.Path.GetExtension(FileName);//获取文件类型后缀名
                    //if ((extension.ToLower() == ".pdf"))
                    //{
                    int fileSize = file.PostedFile.ContentLength;
                    if (fileSize == 0)
                    {
                        base.AlertMessage("The file does not exist！");
                    }
                    else
                    {
                        if (true)//限制大小为1M
                        {

                            string time = DateTime.Now.ToString("yyyyMMddHHmmss");
                            string FileNam_Time = "";
                            int FileIndex = FileName.LastIndexOf("\\");
                            string FName = FileName.Substring(FileIndex + 1);
                            FileNam_Time = time + FName;//日期和名称组合
                            string path = HttpContext.Current.Request.MapPath("../FileUpload/guide/" + FJID + "/");
                            string url = "../FileUpload/guide/" + FJID + "/" + time + FName;
                            DirectoryInfo upDir = new DirectoryInfo(path);
                            if (!upDir.Exists)
                            {
                                upDir.Create();
                            }
                            file.SaveAs(path + FileNam_Time);
                            DataInfo(FJID, FName, path + time, 0, url, (fileSize / 1024.0).ToString("n") + "kb", "", CurrentUser.Id);
                            lbo.WriteLog(CurrentUser.Id, "Upload File:" + FName);
                            // AlertReflashOpener("Already upload");
                            //AlertRedirect("Already upload", "TemplateEdit.aspx?DID=" + Request.QueryString["DID"].ToString());
                            AlertMessage("Already upload");

                            //Model.AttachmentTemplate t = bo.GetModel(int.Parse(Request.QueryString["DID"].ToString()));
                            //FJID = d.UPLOADEDFILE;
                            ////btnUp.Visible = true;
                            //lblUp.Text = "<input type='button'   class='button'  onclick='javascript:PopUpWindow(\"UploadFile.aspx?FJID=" + d.UPLOADEDFILE + "\", 230, 160, 730, 350);'   value='Upload'>";
                            GetFile("");
                        }
                    }
                    //}
                    //else
                    //{
                    //    AlertMessage("Can't upload this file types,Please select a PDF file");
                    //}
                }
                else
                {
                    AlertMessage("Please select accessories！");
                }
            }
        }

        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            // 从事件参数获取排序数据列
            string sortExpression = e.SortExpression.ToString();
            // 假定为排序方向为“顺序”
            string sortDirection = "ASC";
            // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
            if (sortExpression == this.GridView2.Attributes["SortExpression"])
            {
                //获得下一次的排序状态
                sortDirection = (this.GridView2.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
            }
            // 重新设定GridView排序数据列及排序方向
            this.GridView2.Attributes["SortExpression"] = sortExpression;
            this.GridView2.Attributes["SortDirection"] = sortDirection;

            string pic = "";
            pic = sortDirection == "ASC" ? "<img src='../Images/icon/arrowup.gif' />" : "<img src='../Images/icon/arrowdown.gif' />";

            foreach (DataControlField item in GridView2.Columns)
            {
                if (item.SortExpression == sortExpression)
                {
                    item.HeaderText = item.FooterText + " " + pic;
                }
                else
                    item.HeaderText = item.FooterText;
            }

            this.BindGridView();


        }

        private void BindGridView()
        {
            // 获取GridView排序数据列及排序方向
            string sortExpression = this.GridView2.Attributes["SortExpression"];
            string sortDirection = this.GridView2.Attributes["SortDirection"];
            if (sortExpression != null)
            {
                // 调用业务数据获取方法
                string sort = string.Format("  order by lower({0})  {1} ", sortExpression, sortDirection);
                if (sortExpression == "UpTime")
                {
                    sort = string.Format("  order by {0}  {1} ", sortExpression, sortDirection);
                }
                //DataTable dtBind = bo.GetList(sort).Tables[0];
                //// 根据GridView排序数据列及排序方向设置显示的默认数据视图
                //if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
                //{
                //    dtBind.DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
                //}
                //// GridView绑定并显示数据
                //this.GridView2.DataSource = dtBind;
                //this.GridView2.DataBind();
                GetFile(sort);
            }
            else
                GetFile("");
        }
    }
}